package com.example.demo05proxy2;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyUtil {
    public static <T> T createProxy(T userService) {
        T proxy = (T) Proxy.newProxyInstance(ProxyUtil.class.getClassLoader(),
                userService.getClass().getInterfaces(), new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        long start = System.currentTimeMillis();
                        // 真正调用业务对象被代理的方法
                        Object result = method.invoke(userService, args);
                        long end = System.currentTimeMillis();
                        System.out.println(method.getName() + "耗时：" + (end - start) / 1000 + "ms");

                        return result;
                    }
                });
        return proxy;
    }
}
